#ifndef __ARK_FLEX_THREAD_POOL_H__
#define __ARK_FLEX_THREAD_POOL_H__

#include <stdlib.h>
#include <list>
#include <vector>
#include <thread>
#include <memory>
#include <functional>
#include <atomic>
#include "BlockingQueue.h"

namespace Ark
{
    class FlexThreadPool
    {
        enum {
            DEFAULT_RECYCLE_IDLE_TIME = 60 //seconds
        };
    public:
        FlexThreadPool();
        virtual ~FlexThreadPool();
        FlexThreadPool(const FlexThreadPool&) = delete;
        void operator = (const FlexThreadPool&) = delete;

    public:
        void Start(unsigned minThreadCount, unsigned maxThreadCount, unsigned maxIdleSeconds);
        void Stop();
        bool Post(const std::function<void()>& task);

    private:
        bool _Post(BlockingQueue::TaskPtr task);
        void _WorkLoop(int idleSeconds);
        bool _RecycleThread();
        void _PostExitTask();

    private: 
        volatile bool _stop = false;
        std::mutex _mutex;
        unsigned _minThreadCount = 4;
        unsigned _maxThreadCount = 8;
        unsigned _idleSecondsToRecycle = DEFAULT_RECYCLE_IDLE_TIME;
        std::atomic<unsigned> _busyThreadCount;
        std::list<std::shared_ptr<std::thread>> _threads;
        BlockingQueue _taskQueue;

        typedef FlexThreadPool self;
    };
}

#endif  //__ARK_FLEX_THREAD_POOL_H__
